package com.bcpapp.project.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bcpapp.project.constant.RLConstant;
import com.bcpapp.project.model.entity.*;
import com.bcpapp.project.task.TaskServer;
import org.springframework.beans.factory.annotation.Autowired;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Main {



    public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, IOException, BadPaddingException, IllegalBlockSizeException, NoSuchProviderException, InvalidKeyException, ParseException, InterruptedException {


        String ss ="/home/ndr_ych/data/data_jqpw/buyTicket/qinlingsibao/";
        String s2 = StrUtil.subBetween(ss, "buyTicket/", "/");
        String s = StrUtil.subAfter(ss, "buyTicket/",true);
        String s1 = StrUtil.subAfter(ss, "buyTicket/",false);
        System.out.println(s);
        System.out.println(s1);
        System.out.println(s2);
     //   StrUtil.sub(ss,"",ss.length()-1);
        System.out.println(SM4Util.generateKey());
      // System.out.println(SM4Util.encrypt("U4L1wHvQZG09X8tllDAKtA==","610777199707110909"));
      // System.out.println(SM4Util.encrypt("2AW/xR8AfK+1gcaErBAkBg==","12223112341"));
   //
      // System.out.println( SM4Util.decrypt("U4L1wHvQZG09X8tllDAKtA==","9ntr0pPy68sCglYGfZA/LQwfbAf3YWrRcFV6U2GdeBQ="));


        System.out.println(SM4Util.encrypt("2AW/xR8AfK+1gcaErBAkBg==","232126194812010370"));
        System.out.println(SM4Util.encrypt("2AW/xR8AfK+1gcaErBAkBg==","12223112341"));
        //
        System.out.println( SM4Util.decrypt("MQvax0EPRZ6+KfImz7gCqA==","IWBB1sBsbZcziu+j9X+b5fhGIbqt9I7cCd5UAGsFrSU="));

    }

    public static Long getTimeT(String timeString) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(timeString);
        long timestamp = date.getTime();
        System.out.println(timestamp);
        return timestamp;
    }


    /*
     * 区域实时累计人流接口
     * */
    public static void flowsum() {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", "4136727468333852615");
        jsonObject.put("begin", 1699200000);
        jsonObject.put("end", 1699286400);
        jsonObject.put("people_type", "all");
        jsonObject.put("key", "3WVBZ-H5XHJ-JWTFE-X5ROM-CN5HT-FLFU6");
        String result = HttpRequest.post("https://apis.map.qq.com/bigdata/realtime/v1.1/flowsum").header("Content-Type", "application/json")
                .body(jsonObject.toString()).execute().sync().body();

        JSONObject resultJston = new JSONObject(result);
        JSONObject resultData = new JSONObject(resultJston.getStr("data"));
        Flowsum flowsum =new Flowsum();



        resultData.get("out");
        flowsum.setId("4136727468333852615");
        flowsum.setBegin("1699200000");
        flowsum.setEnd("1699286400");
        flowsum.setIn(Integer.valueOf(resultData.get("in").toString()));
        flowsum.setOut(Integer.valueOf(resultData.get("out").toString()));


        System.out.println( flowsum.toStringt());

        File file = new File("D:\\zyapp\\txrl"+"\\"+ "flowsum" + ".bcp");
        FileUtil.appendString(flowsum.toStringt(),file, CharsetUtil.UTF_8);
        FileUtil.appendString("\n",file, CharsetUtil.UTF_8);

    }


    /*
     * https://apis.map.qq.com/bigdata/realtime/v1.1/userprofile
     * 区域实时人口画像接口的
     * */
    public static void userprofile() {
        Set<String> strings = RLConstant.userprofile_Type.keySet();
        String s = strings.toString();
        String aa ="101010,101012,1121,1120,1612,1117,1413,1314,1116,1017,1610,1313,1312,1015,1410,1311,1014,1310,1112,1013,1012,1418,1416,1119,1110,1422,1421,1124,101015,1427";
        System.out.println(s);
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", "4136727468333852615");
        paramMap.put("begin", 1699722000);
        paramMap.put("end", 1699729200);
        paramMap.put("interval", 60);
        paramMap.put("type", aa);
        paramMap.put("people_type", "all");
        paramMap.put("key", "3WVBZ-H5XHJ-JWTFE-X5ROM-CN5HT-FLFU6");
        JSON parse = JSONUtil.parse(paramMap);

        String result = HttpUtil.post("https://apis.map.qq.com/bigdata/realtime/v1.1/userprofile", String.valueOf(parse));

        JSONObject resultJston = new JSONObject(result);

        JSONArray resultArray = new JSONArray(resultJston.get("data"));
        Iterator<Object> iterator = resultArray.stream().iterator();
        while (iterator.hasNext()){
            String time = null;

            Map<String, Object> userprofileAll =new HashMap<>();

            JSONArray tempData = new JSONArray(iterator.next());
            Iterator<Object> tempDataIterator = tempData.stream().iterator();
            while (tempDataIterator.hasNext()){
                JSONArray tempData1 = new JSONArray(tempDataIterator.next());
                for (int i = 0; i < tempData1.size(); i++) {
                    Map<String, Object> tempArr = (Map) JSONUtil.parse(tempData1.get(i));
                    for (int j = 0; j < RLConstant.userprofileList.size(); j++) {
                        if (tempArr.keySet().contains(RLConstant.userprofileList.get(j))){
                            if (tempArr.keySet().contains("time")){
                                time = tempArr.get("time").toString();
                            } else if (tempArr.keySet().contains("常住地")){

                                JSONArray alwaysPathArray = new JSONArray(tempArr.get("常住地"));
                                Iterator<Object> alwaysPathIter = alwaysPathArray.stream().iterator();
                                while (alwaysPathIter.hasNext()){
                                    AlwaysCity alwaysCity = JSONUtil.toBean((JSONObject) alwaysPathIter.next(), AlwaysCity.class);
                                    UserprofileAlwaysPath userprofileAlwaysPath =new UserprofileAlwaysPath() ;
                                    userprofileAlwaysPath.setId("id1");
                                    userprofileAlwaysPath.setTime("time");
                                    userprofileAlwaysPath.setPathType("常住地");
                                    userprofileAlwaysPath.setCity(alwaysCity.getCity());
                                    userprofileAlwaysPath.setDistrict(alwaysCity.getDistrict());
                                    userprofileAlwaysPath.setPercent(alwaysCity.getPercent());
                                    userprofileAlwaysPath.setProperty(alwaysCity.getProperty());
                                    userprofileAlwaysPath.setProvince(alwaysCity.getProvince());

                                    System.out.println(userprofileAlwaysPath.toStringt());
                                }

                                System.out.println("常住地");
                            }else {

                                JSONArray homeCityArr = new JSONArray(tempArr.get("家乡地") );
                                JSONArray alwaysCityArr = new JSONArray( tempArr.get("常驻城市"));

                                JSONArray allCity =new JSONArray();
                                allCity.addAll(homeCityArr);
                                allCity.addAll(alwaysCityArr);

                                Iterator<Object> alwaysPathIter = allCity.stream().iterator();
                                while (alwaysPathIter.hasNext()){
                                    HomeCity homeCity = JSONUtil.toBean((JSONObject) alwaysPathIter.next(), HomeCity.class);
                                    UserprofileHomeAndAlwaysCity userprofileHomeAndAlwaysCity =new UserprofileHomeAndAlwaysCity();

                                    userprofileHomeAndAlwaysCity.setId("idd");
                                    userprofileHomeAndAlwaysCity.setTime("time");
                                    userprofileHomeAndAlwaysCity.setPathType("家乡地");
                                    userprofileHomeAndAlwaysCity.setCity(homeCity.getCity());
                                    userprofileHomeAndAlwaysCity.setPercent(homeCity.getPercent());
                                    userprofileHomeAndAlwaysCity.setProperty(homeCity.getProperty());
                                    userprofileHomeAndAlwaysCity.setProvince(homeCity.getProvince());

                                    System.out.println(userprofileHomeAndAlwaysCity.toStringt());
                                }
                                System.out.println("家乡地");
                            }
                            System.out.println(tempArr);
                        };
                        tempArr.remove(RLConstant.userprofileList.get(j));

                    }

                    if (tempArr.size()>0){
                        userprofileAll.putAll(tempArr);
                    }
                  //  System.out.println(tempArr.size());
                   // System.out.println(tempArr.toString());
                }

            }
            System.out.println(userprofileAll);

            String finalTime = time;
            userprofileAll.entrySet().forEach(entry ->{
                JSONArray ja =new JSONArray(entry.getValue());
                Iterator<Object> iterator1 = ja.stream().iterator();
                while (iterator1.hasNext()){
                    Tgi tgi = JSONUtil.toBean((JSONObject) iterator1.next(), Tgi.class);
                    UserprofileOtherTgi userprofileOtherTgi =new UserprofileOtherTgi();
                    userprofileOtherTgi.setId("id");
                    userprofileOtherTgi.setTime(finalTime);
                    userprofileOtherTgi.setDataType(entry.getKey());
                    userprofileOtherTgi.setPercent(tgi.getPercent());
                    userprofileOtherTgi.setProperty(tgi.getProperty());
                    userprofileOtherTgi.setTgi_percent(tgi.getTgi_percent());
                    System.out.println(userprofileOtherTgi.toStringt());
                }
                // System.out.println(            entry.getValue().toString());
            });
            System.out.println("++++++++++++++");
        }


        System.out.println(result);


    }


    /*
     * 区划迁入迁出驻留分析接口
     * */
    public static String populationsituationday() {

        File file = new File("D:\\zyapp\\txrl"+"\\"+ "populationsituationday" + ".bcp");

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("date", "2023-11-06");
        paramMap.put("adcode", "610100");
        paramMap.put("key", "3WVBZ-H5XHJ-JWTFE-X5ROM-CN5HT-FLFU6");

        JSON parse = JSONUtil.parse(paramMap);

        String result = HttpUtil.post("https://apis.map.qq.com/bigdata/realtime/v1/populationsituationday", String.valueOf(parse));
        JSONObject resultJston = new JSONObject(result);
        JSONObject resultData = new JSONObject(resultJston.getStr("result"));


        Set<String> personTypeSet = resultData.keySet();

        //获取人口类型
        for (String personType : personTypeSet) {
            JSONObject userprofile = new JSONObject(resultData.get(personType));
            String populationCount = userprofile.get("population").toString();
            Set<String> userprofileKeySet = userprofile.keySet();
            userprofileKeySet.remove("population");
            //便利画像
            for (String userprofileKey : userprofileKeySet) {
                JSONObject userprofileDetail = new JSONObject(userprofile.get(userprofileKey));
                Set<String> detailsSet = userprofileDetail.keySet();

                //便利画像属性
                for (String detailsKey : detailsSet) {
                    JSONObject jsonObject = new JSONObject(userprofileDetail.get(detailsKey));
                    Map<String, Object> checkNumber = (Map) JSONUtil.parse(jsonObject);
                    //画像属性Key value
                    for (String key : checkNumber.keySet()) {
                        RlPopulationsituationday rlPopulationsituationday = new RlPopulationsituationday();
                        String value = checkNumber.get(key).toString();
                        //  System.out.println("key="+key+" vlaue="+value);
                        rlPopulationsituationday.setPersonType(personType);
                        rlPopulationsituationday.setPersonCount(populationCount);
                        rlPopulationsituationday.setUserprofileType(RLConstant.PopulationsituationdayMap.get(detailsKey));
                        rlPopulationsituationday.setUserprofileContent(key);
                        rlPopulationsituationday.setUserprofilePcount(value);
                        rlPopulationsituationday.setCreateTime("2023-11-06");
                        System.out.println(rlPopulationsituationday.toStringt());
                        //System.out.println(rlPopulationsituationday);

                        FileUtil.appendString(rlPopulationsituationday.toStringt(),file, CharsetUtil.UTF_8);
                        FileUtil.appendString("\n",file, CharsetUtil.UTF_8);


                    }

                }
                //  System.out.println(userprofileDetail);
            }
        }

        return result;
    }

    /*
     * https://apis.map.qq.com/bigdata/realtime/v1/migrationuserprofile
     * 区划迁徙分析
     * */
    public static void migrationuserprofile() {


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("date", "2023-11-02");
        jsonObject.put("o_adcode", "410200");
        jsonObject.put("d_adcode", "610100");
        jsonObject.put("count_type", 1);
        jsonObject.put("is_userprofile", 1);
        jsonObject.put("key", "3WVBZ-H5XHJ-JWTFE-X5ROM-CN5HT-FLFU6");
        String result = HttpRequest.post("https://apis.map.qq.com/bigdata/realtime/v1/migrationuserprofile").header("Content-Type", "application/json")
                .body(jsonObject.toString()).timeout(30 * 1000).execute().body();
        JSONObject resultJston = new JSONObject(result);
        JSONObject resultData = new JSONObject(resultJston.getStr("result"));
        String population = resultData.get("population").toString();
        JSONObject userprofileJson = new JSONObject(resultData.get("userprofile"));
        JSONObject ageJson = new JSONObject(userprofileJson.get("age"));

        Map<String,String> ageMap =   (Map) JSONUtil.parse(ageJson);
        JSONObject genderJson = new JSONObject(userprofileJson.get("gender"));
        Map<String,String> genderMap =   (Map) JSONUtil.parse(genderJson);
        JSONObject trafficJson = new JSONObject(userprofileJson.get("traffic"));
        Map<String,String> trafficMap =   (Map) JSONUtil.parse(trafficJson);

        Map<String,Map> allMap =new HashMap<>();
        allMap.put("age",ageMap);
        allMap.put("gender",genderMap);
        allMap.put("traffic",trafficMap);




        allMap.entrySet().forEach(entry ->{
            Map<String,String> mm = entry.getValue();
                mm.entrySet().forEach(entryset ->{
                Migrationuserprofile migrationuserprofile =new Migrationuserprofile();
                migrationuserprofile.setTime("time");
                migrationuserprofile.setO_adcode("410200");
                migrationuserprofile.setD_adcode("610100");
                migrationuserprofile.setPopulation(population);
                migrationuserprofile.setUserprofile(entry.getKey());
                migrationuserprofile.setUserprofileType(entryset.getKey());
                migrationuserprofile.setValue(String.valueOf(entryset.getValue()));

                    System.out.println(migrationuserprofile.toStringt());
            });

        });








    }


    /*

    区划迁徙总览接口的
    * https://apis.map.qq.com/bigdata/realtime/v1/adcodemigration
    * */
    public static void  adcodemigration() {


        File file = new File("D:\\zyapp\\txrl"+"\\"+ "adcodemigration" + ".bcp");

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("date", "2023-11-02");
        paramMap.put("adcode", "610100");
        paramMap.put("key", "3WVBZ-H5XHJ-JWTFE-X5ROM-CN5HT-FLFU6");

        JSON parse = JSONUtil.parse(paramMap);

        String result = HttpUtil.post("https://apis.map.qq.com/bigdata/realtime/v1/adcodemigration", String.valueOf(parse));
        JSONObject resultJston = new JSONObject(result);
        JSONObject resultData = new JSONObject(resultJston.getStr("result"));
        for (String key: RLConstant.adcodemigrationKey) {
            JSONObject adcodemigrationValue = new JSONObject(resultData.getStr(key));
            String population = adcodemigrationValue.get("population").toString();
            JSONObject traffic = new JSONObject(adcodemigrationValue.get("traffic"));
            String carTraffic = traffic.get("car").toString();
            String plainTraffic = traffic.get("plane").toString();
            String trainTraffic = traffic.get("train").toString();
            for (String vKey: RLConstant.adcodemigrationValueKey) {
                JSONArray array =new JSONArray(adcodemigrationValue.get(vKey));
                Iterator<Object> iterator = array.stream().iterator();
                while (iterator.hasNext()){
                    JSONObject pointData = new JSONObject(iterator.next());
                    Migration migration = JSONUtil.toBean(pointData, Migration.class);
                    Adcodemigration adcodemigration =new Adcodemigration();
                    adcodemigration.setDate("2023-11-02");
                    adcodemigration.setAdcode("610100");
                    adcodemigration.setDataType(key);
                    adcodemigration.setPopulation(population);
                    adcodemigration.setSourceType(vKey);
                    adcodemigration.setSourceAdcode(migration.getAdcode());
                    adcodemigration.setSourcePopulation(migration.getPopulation());
                    adcodemigration.setCarTraffic(carTraffic);
                    adcodemigration.setTrainTraffic(trainTraffic);
                    adcodemigration.setPlaneTraffic(plainTraffic);
                    System.out.println(adcodemigration.toStringt());

                    FileUtil.appendString(adcodemigration.toStringt(),file, CharsetUtil.UTF_8);
                    FileUtil.appendString("\n",file, CharsetUtil.UTF_8);



                }


            }
            System.out.println("================================================");
        }


        System.out.println(result);

    }


    /*
     * 区域实时人口热力
     *
     * https://apis.map.qq.com/bigdata/realtime/v1.1/locationpoint
     * */
    public static void locationpoint() {

        File file = new File("D:\\zyapp\\txrl"+"\\"+ "locationpoint" + ".bcp");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", "4136727468333852615");
        jsonObject.put("begin", 1699200000);
        jsonObject.put("end", 1699286400);
        jsonObject.put("interval", 5);
        jsonObject.put("people_type", "all");
        jsonObject.put("key", "3WVBZ-H5XHJ-JWTFE-X5ROM-CN5HT-FLFU6");
        System.out.println("调用接口");
        try {
            String result = HttpRequest.post("https://apis.map.qq.com/bigdata/realtime/v1.1/locationpoint").header("Content-Type", "application/json")
                    .body(jsonObject.toString()).timeout(30 * 1000).execute().body();
            JSONObject resultJston = new JSONObject(result);
            JSONArray resultData = new JSONArray(resultJston.getStr("data"));
            Iterator<Object> iterator = resultData.stream().iterator();
            while (iterator.hasNext()){
                JSONObject pointData = new JSONObject(iterator.next());
                String time = pointData.get("time").toString();
                JSONArray pointDetails = new JSONArray(pointData.get("points"));
                Iterator<Object> pointDetailsIterator = pointDetails.stream().iterator();
                while (pointDetailsIterator.hasNext()){
                    JSONObject pointOne = new JSONObject(pointDetailsIterator.next());
                    Points points = JSONUtil.toBean(pointOne, Points.class);
                    Locationpoint locationpoint =new Locationpoint();
                    locationpoint.setId("4136727468333852615");
                    locationpoint.setPeopleType("活跃人口");
                    locationpoint.setTime(time);
                    locationpoint.setLat(points.getLat());
                    locationpoint.setLng(points.getLng());
                    locationpoint.setWeight(points.getWeight());
                    System.out.println(locationpoint.toStringt());


                    FileUtil.appendString(locationpoint.toStringt(),file, CharsetUtil.UTF_8);
                    FileUtil.appendString("\n",file, CharsetUtil.UTF_8);


                }


            }
        }catch (Exception e){
            throw  new RuntimeException();
        }


    }


    /*
     *
     * 区域实时人流接口
     *
     * https://apis.map.qq.com/bigdata/realtime/v1.1/flow
     * */
    public static void flow() {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", "4136727468333852615");
        jsonObject.put("begin", 1698969600);
        jsonObject.put("end", 1698984000);
        jsonObject.put("interval", 5);
        jsonObject.put("people_type", "all");
        jsonObject.put("key", "3WVBZ-H5XHJ-JWTFE-X5ROM-CN5HT-FLFU6");
        String result = HttpRequest.post("https://apis.map.qq.com/bigdata/realtime/v1.1/flow").header("Content-Type", "application/json")
                .body(jsonObject.toString()).timeout(60 * 1000).execute().body();
        JSONObject resultJston = new JSONObject(result);
        JSONArray resultData = new JSONArray(resultJston.getStr("data"));
        Iterator<Object> iterator = resultData.stream().iterator();
        while (iterator.hasNext()){
            JSONObject flowData = new JSONObject(iterator.next());
            Flow flow =new Flow();
            flow.setId("4136727468333852615");
            flow.setIn(flowData.get("in").toString());
            flow.setOut(flowData.get("out").toString());
            flow.setTime(flowData.get("time").toString());


            System.out.println(flow.toStringt());
        }
        // System.out.println(s);
        System.out.println(result);
    }

    /*
     *
     *   https://apis.map.qq.com/bigdata/realtime/v1.1/population
     * 据区域实时人数接口
     * */
    public static void population() {
        File file = new File("D:\\zyapp\\txrl"+"\\"+ "population" + ".bcp");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", "4136727468333852615");
        jsonObject.put("begin", 1699200000);
        jsonObject.put("end", 1699286400);
        jsonObject.put("interval", 5);
        jsonObject.put("people_type", "all");
        jsonObject.put("key", "3WVBZ-H5XHJ-JWTFE-X5ROM-CN5HT-FLFU6");
        String result = HttpRequest.post("https://apis.map.qq.com/bigdata/realtime/v1.1/population").header("Content-Type", "application/json")
                .body(jsonObject.toString()).timeout(30 * 1000).execute().body();
        JSONObject resultJston = new JSONObject(result);
        JSONArray data = (JSONArray) resultJston.get("data");

        for(int i=0 ; i < data.size() ;i++)
        {
            JSONObject dataDetail = data.getJSONObject(i);
            Population population =new Population();
            population.setId("4136727468333852615");
             population.setTime(dataDetail.get("time").toString());
            population.setValue( dataDetail.get("value").toString());
            System.out.println(population.toStringt());
            FileUtil.appendString(population.toStringt(),file, CharsetUtil.UTF_8);
            FileUtil.appendString("\n",file, CharsetUtil.UTF_8);



        }



    }

    /*
     *
     *
     * https://apis.map.qq.com/bigdata/realtime/v1.1/predictpopulation
     * 区域实时人数预测
     * */
    public  static void predictpopulation() {
        File file = new File("D:\\zyapp\\txrl"+"\\"+ "predictpopulation" + ".bcp");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", "4136727468333852615");
        jsonObject.put("interval", 10);
        jsonObject.put("people_type", "all");
        jsonObject.put("key", "3WVBZ-H5XHJ-JWTFE-X5ROM-CN5HT-FLFU6");
        String result = HttpRequest.post("https://apis.map.qq.com/bigdata/realtime/v1.1/predictpopulation").header("Content-Type", "application/json")
                .body(jsonObject.toString()).timeout(30 * 1000).execute().body();
        System.out.println(result);

        JSONObject resultJston = new JSONObject(result);
        JSONArray data = (JSONArray) resultJston.get("data");

        for(int i=0 ; i < data.size() ;i++)
        {

            Map<String,String> mapdetails =  (Map<String, String>) data.get(i);

            mapdetails.entrySet().forEach(entry ->{
                Population population =new Population();
                population.setId("4136727468333852615");
                population.setTime(entry.getKey());
                population.setValue( entry.getValue() );
                System.out.println(population.toStringt());
                FileUtil.appendString(population.toStringt(),file, CharsetUtil.UTF_8);
                FileUtil.appendString("\n",file, CharsetUtil.UTF_8);

            });




        }
    }

}
